<template>
  <div class="route-weather-container">
    <!-- 路线信息头部 -->
    <div class="route-header">
      <div class="route-info">
        <div class="route-points">
          <div class="point start-point">
            <el-icon><Location /></el-icon>
            <span class="point-label">起点:</span>
            <span class="point-value">{{ startAddress }}</span>
          </div>
          <div class="route-arrow">
            <el-icon><Right /></el-icon>
          </div>
          <div class="point end-point">
            <el-icon><Location /></el-icon>
            <span class="point-label">终点:</span>
            <span class="point-value">{{ endAddress }}</span>
          </div>
        </div>
        <div class="route-distance" v-if="routeDistance">
          <el-icon><TrendCharts /></el-icon>
          <span>总距离: {{ routeDistance }}km</span>
        </div>
      </div>
      <div class="route-controls">
        <el-button @click="refreshWeather" :loading="loading" type="primary">
          <el-icon><Refresh /></el-icon>
          刷新天气
        </el-button>
      </div>
    </div>

    <!-- 路线预警总览 -->
    <div class="route-alerts-overview" v-if="routeAlerts.length > 0">
      <h3 class="overview-title">
        <el-icon><Warning /></el-icon>
        路线天气预警总览
      </h3>
      <div class="overview-alerts">
        <div 
          v-for="(alert, index) in routeAlerts" 
          :key="index"
          class="overview-alert-item"
          :class="`alert-${alert.level}`"
        >
          <div class="alert-icon">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="alert-content">
            <div class="alert-title">{{ alert.title }}</div>
            <div class="alert-description">{{ alert.description }}</div>
            <div class="alert-locations">{{ alert.locations.join(' → ') }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 中间点天气详情 -->
    <div class="middle-points-weather">
      <h3 class="section-title">
        <el-icon><Calendar /></el-icon>
        路线中间点天气详情
      </h3>
      <div class="points-grid">
        <div 
          v-for="(point, index) in middlePoints" 
          :key="index"
          class="weather-point-card"
          :class="{ 'loading': point.loading, 'error': point.error }"
        >
          <div class="point-header">
            <div class="point-info">
              <div class="point-name">{{ point.name }}</div>
              <div class="point-distance">距离起点: {{ point.distanceFromStart }}km</div>
            </div>
            <div class="point-status">
              <el-icon v-if="point.loading" class="loading-icon"><Loading /></el-icon>
              <el-icon v-else-if="point.error" class="error-icon"><Warning /></el-icon>
              <el-icon v-else class="success-icon"><Check /></el-icon>
            </div>
          </div>

          <!-- 天气信息 -->
          <div class="weather-info" v-if="point.weather && !point.loading && !point.error">
            <div class="current-weather">
              <div class="temperature">
                <span class="temp-value">{{ point.weather.temperature }}</span>
                <span class="temp-unit">°C</span>
              </div>
              <div class="weather-desc">
                <span class="weather-text">{{ point.weather.description }}</span>
              </div>
             
            </div>

            <div class="weather-details">
              <div class="detail-item">
                <el-icon><Sunny /></el-icon>
                <span>湿度: {{ point.weather.humidity }}%</span>
              </div>
              <div class="detail-item">
                <el-icon><WindPower /></el-icon>
                <span>风速: {{ point.weather.windSpeed }} m/s</span>
              </div>
              <div class="detail-item">
                <el-icon><Compass /></el-icon>
                <span>风向: {{ point.weather.windDirection }}</span>
              </div>
              <div class="detail-item">
                <el-icon><View /></el-icon>
                <span>能见度: {{ point.weather.visibility }} km</span>
              </div>
            </div>
          </div>

          <!-- 该点位的天气预警 -->
          <div class="point-alerts" v-if="point.alerts && point.alerts.length > 0">
            <div 
              v-for="(alert, alertIndex) in point.alerts" 
              :key="alertIndex"
              class="point-alert-item"
              :class="`alert-${alert.level}`"
            >
              <div class="alert-icon">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="alert-content">
                <div class="alert-title">{{ alert.title }}</div>
                <div class="alert-description">{{ alert.description }}</div>
              </div>
            </div>
          </div>

          <!-- 错误信息 -->
          <div class="error-info" v-if="point.error">
            <el-icon class="error-icon"><Warning /></el-icon>
            <span>{{ point.error }}</span>
            <el-button @click="refreshPointWeather(index)" size="small" type="primary">重试</el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading && middlePoints.length === 0" class="loading-container">
      <el-card>
        <div class="loading-content">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>正在获取路线天气数据...</span>
        </div>
      </el-card>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-container">
      <el-card>
        <div class="error-content">
          <el-icon class="error-icon"><Warning /></el-icon>
          <span>{{ error }}</span>
          <el-button @click="refreshWeather" type="primary" size="small">重试</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Location, Right, TrendCharts, Refresh, Warning, Calendar,
  Loading, Check, Sunny, WindPower, Compass, View
} from '@element-plus/icons-vue'
import WeatherService, { type WeatherResponse } from '../api/weather'

// 接口定义
interface WeatherData {
  temperature: string
  description: string
  humidity: string
  windSpeed: string
  windDirection: string
  visibility: string
  rainfall: number
}

interface WeatherAlert {
  level: 'low' | 'medium' | 'high' | 'severe'
  title: string
  description: string
  type: 'rain' | 'wind' | 'temperature' | 'visibility' | 'storm'
}

interface MiddlePoint {
  name: string
  latitude: number
  longitude: number
  distanceFromStart: number
  weather?: WeatherData
  alerts?: WeatherAlert[]
  loading: boolean
  error?: string
}

interface RouteAlert {
  level: 'low' | 'medium' | 'high' | 'severe'
  title: string
  description: string
  locations: string[]
  type: 'rain' | 'wind' | 'temperature' | 'visibility' | 'storm'
}

// Props
interface Props {
  startAddress: string
  endAddress?: string
}

const props = withDefaults(defineProps<Props>(), {
  endAddress: '北京'
})

// 响应式数据
const loading = ref(false)
const error = ref('')
const middlePoints = ref<MiddlePoint[]>([])
const routeDistance = ref(0)
const routeAlerts = ref<RouteAlert[]>([])

// 真实城市坐标数据库（包含国际城市）
const cityCoordinates: { [key: string]: { lat: number, lng: number, name: string } } = {
  // 中国城市
  '北京': { lat: 39.9042, lng: 116.4074, name: '北京' },
  '上海': { lat: 31.2304, lng: 121.4737, name: '上海' },
  '广州': { lat: 23.1291, lng: 113.2644, name: '广州' },
  '深圳': { lat: 22.5431, lng: 114.0579, name: '深圳' },
  '杭州': { lat: 30.2741, lng: 120.1551, name: '杭州' },
  '南京': { lat: 32.0603, lng: 118.7969, name: '南京' },
  '成都': { lat: 30.5728, lng: 104.0668, name: '成都' },
  '武汉': { lat: 30.5928, lng: 114.3055, name: '武汉' },
  '西安': { lat: 34.3416, lng: 108.9398, name: '西安' },
  '重庆': { lat: 29.4316, lng: 106.9123, name: '重庆' },
  '天津': { lat: 39.3434, lng: 117.3616, name: '天津' },
  '苏州': { lat: 31.2989, lng: 120.5853, name: '苏州' },
  '青岛': { lat: 36.0671, lng: 120.3826, name: '青岛' },
  '大连': { lat: 38.9140, lng: 121.6147, name: '大连' },
  '厦门': { lat: 24.4798, lng: 118.0819, name: '厦门' },
  '福州': { lat: 26.0745, lng: 119.2965, name: '福州' },
  '济南': { lat: 36.6512, lng: 117.1201, name: '济南' },
  '郑州': { lat: 34.7466, lng: 113.6254, name: '郑州' },
  '长沙': { lat: 28.2278, lng: 112.9388, name: '长沙' },
  '南昌': { lat: 28.6820, lng: 115.8579, name: '南昌' },
  '合肥': { lat: 31.8206, lng: 117.2272, name: '合肥' },
  '石家庄': { lat: 38.0428, lng: 114.5149, name: '石家庄' },
  '太原': { lat: 37.8706, lng: 112.5489, name: '太原' },
  '呼和浩特': { lat: 40.8414, lng: 111.7519, name: '呼和浩特' },
  '沈阳': { lat: 41.8057, lng: 123.4315, name: '沈阳' },
  '长春': { lat: 43.8171, lng: 125.3235, name: '长春' },
  '哈尔滨': { lat: 45.7732, lng: 126.6577, name: '哈尔滨' },
  '昆明': { lat: 25.0389, lng: 102.7183, name: '昆明' },
  '贵阳': { lat: 26.6470, lng: 106.6302, name: '贵阳' },
  '南宁': { lat: 22.8170, lng: 108.3669, name: '南宁' },
  '海口': { lat: 20.0444, lng: 110.1999, name: '海口' },
  '兰州': { lat: 36.0611, lng: 103.8343, name: '兰州' },
  '西宁': { lat: 36.6232, lng: 101.7782, name: '西宁' },
  '银川': { lat: 38.4872, lng: 106.2309, name: '银川' },
  '乌鲁木齐': { lat: 43.8256, lng: 87.6168, name: '乌鲁木齐' },
  '拉萨': { lat: 29.6520, lng: 91.1721, name: '拉萨' },
  
  // 国际城市
  'Sweden': { lat: 59.3293, lng: 18.0686, name: '瑞典' },
  'Stockholm': { lat: 59.3293, lng: 18.0686, name: '斯德哥尔摩' },
 
  'Germany': { lat: 52.5200, lng: 13.4050, name: '德国' },
  'Berlin': { lat: 52.5200, lng: 13.4050, name: '柏林' },
  'France': { lat: 48.8566, lng: 2.3522, name: '法国' },
  'Paris': { lat: 48.8566, lng: 2.3522, name: '巴黎' },
  'UK': { lat: 51.5074, lng: -0.1278, name: '英国' },
  'London': { lat: 51.5074, lng: -0.1278, name: '伦敦' },
  'USA': { lat: 40.7128, lng: -74.0060, name: '美国' },
  'New York': { lat: 40.7128, lng: -74.0060, name: '纽约' },
  'Japan': { lat: 35.6762, lng: 139.6503, name: '日本' },
  'Tokyo': { lat: 35.6762, lng: 139.6503, name: '东京' },
  'South Korea': { lat: 37.5665, lng: 126.9780, name: '韩国' },
  'Seoul': { lat: 37.5665, lng: 126.9780, name: '首尔' },
  'Russia': { lat: 55.7558, lng: 37.6176, name: '俄罗斯' },
  'Moscow': { lat: 55.7558, lng: 37.6176, name: '莫斯科' },
  'India': { lat: 28.6139, lng: 77.2090, name: '印度' },
  'New Delhi': { lat: 28.6139, lng: 77.2090, name: '新德里' },
  'Australia': { lat: -33.8688, lng: 151.2093, name: '澳大利亚' },
  'Sydney': { lat: -33.8688, lng: 151.2093, name: '悉尼' },
  'Canada': { lat: 43.6532, lng: -79.3832, name: '加拿大' },
  'Toronto': { lat: 43.6532, lng: -79.3832, name: '多伦多' },
  'Brazil': { lat: -23.5505, lng: -46.6333, name: '巴西' },
  'Sao Paulo': { lat: -23.5505, lng: -46.6333, name: '圣保罗' },
  'Mexico': { lat: 19.4326, lng: -99.1332, name: '墨西哥' },
  'Mexico City': { lat: 19.4326, lng: -99.1332, name: '墨西哥城' },
  'Italy': { lat: 41.9028, lng: 12.4964, name: '意大利' },
  'Rome': { lat: 41.9028, lng: 12.4964, name: '罗马' },
  'Spain': { lat: 40.4168, lng: -3.7038, name: '西班牙' },
  'Madrid': { lat: 40.4168, lng: -3.7038, name: '马德里' },
  'Netherlands': { lat: 52.3676, lng: 4.9041, name: '荷兰' },
  'Amsterdam': { lat: 52.3676, lng: 4.9041, name: '阿姆斯特丹' },
  'Belgium': { lat: 50.8503, lng: 4.3517, name: '比利时' },
  'Brussels': { lat: 50.8503, lng: 4.3517, name: '布鲁塞尔' },
  'Switzerland': { lat: 46.9481, lng: 7.4474, name: '瑞士' },
  'Zurich': { lat: 46.9481, lng: 7.4474, name: '苏黎世' },
  'Austria': { lat: 48.2082, lng: 16.3738, name: '奥地利' },
  'Vienna': { lat: 48.2082, lng: 16.3738, name: '维也纳' },
  'Poland': { lat: 52.2297, lng: 21.0122, name: '波兰' },
  'Warsaw': { lat: 52.2297, lng: 21.0122, name: '华沙' },
  'Czech Republic': { lat: 50.0755, lng: 14.4378, name: '捷克' },
  'Prague': { lat: 50.0755, lng: 14.4378, name: '布拉格' },
  'Hungary': { lat: 47.4979, lng: 19.0402, name: '匈牙利' },
  'Budapest': { lat: 47.4979, lng: 19.0402, name: '布达佩斯' },
  'Romania': { lat: 44.4268, lng: 26.1025, name: '罗马尼亚' },
  'Bucharest': { lat: 44.4268, lng: 26.1025, name: '布加勒斯特' },
  'Bulgaria': { lat: 42.6977, lng: 23.3219, name: '保加利亚' },
  'Sofia': { lat: 42.6977, lng: 23.3219, name: '索菲亚' },
  'Greece': { lat: 37.9755, lng: 23.7348, name: '希腊' },
  'Athens': { lat: 37.9755, lng: 23.7348, name: '雅典' },
  'Turkey': { lat: 41.0082, lng: 28.9784, name: '土耳其' },
  'Istanbul': { lat: 41.0082, lng: 28.9784, name: '伊斯坦布尔' },
  'Ukraine': { lat: 50.4501, lng: 30.5234, name: '乌克兰' },
  'Kiev': { lat: 50.4501, lng: 30.5234, name: '基辅' },
  'Finland': { lat: 60.1699, lng: 24.9384, name: '芬兰' },
  'Helsinki': { lat: 60.1699, lng: 24.9384, name: '赫尔辛基' },
  'Norway': { lat: 59.9139, lng: 10.7522, name: '挪威' },
  'Oslo': { lat: 59.9139, lng: 10.7522, name: '奥斯陆' },
  'Denmark': { lat: 55.6761, lng: 12.5683, name: '丹麦' },
  'Copenhagen': { lat: 55.6761, lng: 12.5683, name: '哥本哈根' }
}

// 计算路线中间的真实城市
const calculateMiddleCities = (startLat: number, startLng: number, endLat: number, endLng: number) => {
  const points: MiddlePoint[] = []
  
  // 使用更精确的距离计算（考虑地球曲率）
  const toRadians = (degrees: number) => degrees * (Math.PI / 180)
  const R = 6371 // 地球半径（公里）
  
  const dLat = toRadians(endLat - startLat)
  const dLng = toRadians(endLng - startLng)
  const a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(toRadians(startLat)) * Math.cos(toRadians(endLat)) *
            Math.sin(dLng/2) * Math.sin(dLng/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  const distance = R * c
  
  routeDistance.value = Math.round(distance)
  console.log('计算路线总距离:', distance, 'km')
  
  // 计算三个中间点坐标
  const middleCoords = []
  for (let i = 1; i <= 3; i++) {
    const ratio = i / 4 // 1/4, 2/4, 3/4 位置
    const lat = startLat + (endLat - startLat) * ratio
    const lng = startLng + (endLng - startLng) * ratio
    const pointDistance = distance * ratio
    
    middleCoords.push({
      lat,
      lng,
      distance: Math.round(pointDistance)
    })
    
    console.log(`中间点${i}坐标:`, lat, lng, '距离:', pointDistance, 'km')
  }
  
  // 为每个中间点找到最近的真实城市
  middleCoords.forEach((coord, index) => {
    let nearestCity = ''
    let minDistance = Infinity
    
    // 查找最近的城市
    Object.entries(cityCoordinates).forEach(([cityName, cityData]) => {
      const cityDistance = Math.sqrt(
        Math.pow(coord.lat - cityData.lat, 2) + Math.pow(coord.lng - cityData.lng, 2)
      )
      
      if (cityDistance < minDistance) {
        minDistance = cityDistance
        nearestCity = cityName
      }
    })
    
    console.log(`中间点${index + 1}最近城市:`, nearestCity, '距离:', minDistance)
    
    // 如果找到了最近的城市，使用该城市的坐标
    if (nearestCity && cityCoordinates[nearestCity]) {
      const cityData = cityCoordinates[nearestCity]
      points.push({
        name: cityData.name,
        latitude: cityData.lat,
        longitude: cityData.lng,
        distanceFromStart: coord.distance,
        loading: false,
        error: undefined
      })
    } else {
      // 如果没有找到合适的城市，使用计算出的坐标
      points.push({
        name: `中间点${index + 1}`,
        latitude: coord.lat,
        longitude: coord.lng,
        distanceFromStart: coord.distance,
        loading: false,
        error: undefined
      })
    }
  })
  
  return points
}

// 地址转坐标
const addressToCoordinates = async (address: string) => {
  console.log('正在解析地址:', address)
  
  // 尝试精确匹配
  if (cityCoordinates[address]) {
    console.log('精确匹配到:', cityCoordinates[address])
    return { lat: cityCoordinates[address].lat, lng: cityCoordinates[address].lng }
  }
  
  // 尝试包含匹配
  for (const [cityName, coords] of Object.entries(cityCoordinates)) {
    if (address.toLowerCase().includes(cityName.toLowerCase()) || cityName.toLowerCase().includes(address.toLowerCase())) {
      console.log('包含匹配到:', cityName, coords)
      return { lat: coords.lat, lng: coords.lng }
    }
  }
  
  // 如果没有匹配到，返回默认坐标（北京）
  console.log('未匹配到地址，使用默认坐标（北京）')
  return { lat: 39.9042, lng: 116.4074 }
}

// 解析天气数据
const parseWeatherData = (weatherResponse: WeatherResponse): WeatherData => {
  const data = weatherResponse.data
  const lines = data.split('\n')
  
  const weatherInfo: any = {}
  
  for (const line of lines) {
    const trimmedLine = line.trim()
    
    if ((trimmedLine.includes('温度：') || trimmedLine.includes('温度:')) && !weatherInfo.temperature) {
      const tempValue = trimmedLine.split(/[：:]/)[1].replace('°C', '').trim()
      weatherInfo.temperature = tempValue
    } else if (trimmedLine.includes('天气：')) {
      weatherInfo.description = trimmedLine.split('：')[1]
    } else if (trimmedLine.includes('湿度：')) {
      weatherInfo.humidity = trimmedLine.split('：')[1].replace('%', '')
    } else if (trimmedLine.includes('风速：')) {
      weatherInfo.windSpeed = trimmedLine.split('：')[1].replace(' m/s', '')
    } else if (trimmedLine.includes('风向：')) {
      weatherInfo.windDirection = trimmedLine.split('：')[1]
    } else if (trimmedLine.includes('能见度：')) {
      weatherInfo.visibility = trimmedLine.split('：')[1].replace(' km', '')
    } else if (trimmedLine.includes('降雨量：')) {
      const rainfallValue = trimmedLine.split('：')[1].trim()
      weatherInfo.rainfall = rainfallValue === '无降雨' ? 0 : parseFloat(rainfallValue.replace(' mm', ''))
    }
  }
  
  return weatherInfo
}

// 检测天气预警
const checkWeatherAlerts = (weather: WeatherData): WeatherAlert[] => {
  const alerts: WeatherAlert[] = []
  const now = new Date()
  
  // 温度预警 - 进一步降低阈值
  const temperature = parseFloat(weather.temperature)
  if (temperature >= 25) {
    alerts.push({
      level: 'high',
      title: '高温预警',
      description: `当前温度${temperature}°C，物流运输需注意货物防热保护，建议调整运输时间避开高温时段`,
      type: 'temperature'
    })
  } else if (temperature >= 20) {
    alerts.push({
      level: 'medium',
      title: '温度提醒',
      description: `当前温度${temperature}°C，温度较高，建议注意货物通风散热`,
      type: 'temperature'
    })
  } else if (temperature <= 0) {
    alerts.push({
      level: 'high',
      title: '低温预警',
      description: `当前温度${temperature}°C，物流运输需注意货物防冻保护，建议使用保温包装`,
      type: 'temperature'
    })
  } else if (temperature <= 5) {
    alerts.push({
      level: 'medium',
      title: '低温提醒',
      description: `当前温度${temperature}°C，温度较低，建议注意货物保温`,
      type: 'temperature'
    })
  }
  
  // 降雨预警 - 进一步降低阈值
  const rainfall = weather.rainfall
  if (rainfall > 20) {
    alerts.push({
      level: 'severe',
      title: '暴雨预警',
      description: `降雨量${rainfall}mm，物流运输严重受阻，建议暂停运输或选择铁路/航空运输`,
      type: 'rain'
    })
  } else if (rainfall > 10) {
    alerts.push({
      level: 'high',
      title: '大雨预警',
      description: `降雨量${rainfall}mm，道路运输受影响，建议降低车速，注意货物防水保护`,
      type: 'rain'
    })
  } else if (rainfall > 3) {
    alerts.push({
      level: 'medium',
      title: '中雨预警',
      description: `降雨量${rainfall}mm，运输需谨慎，建议加强货物防潮措施`,
      type: 'rain'
    })
  } else if (rainfall > 0) {
    alerts.push({
      level: 'low',
      title: '小雨提醒',
      description: `降雨量${rainfall}mm，运输基本正常，建议注意货物防潮`,
      type: 'rain'
    })
  }
  
  // 风速预警 - 进一步降低阈值
  const windSpeed = parseFloat(weather.windSpeed)
  if (windSpeed >= 12) {
    alerts.push({
      level: 'severe',
      title: '大风预警',
      description: `风速${windSpeed}m/s，物流运输严重危险，建议暂停大型车辆运输，注意货物固定`,
      type: 'wind'
    })
  } else if (windSpeed >= 8) {
    alerts.push({
      level: 'high',
      title: '强风预警',
      description: `风速${windSpeed}m/s，运输需谨慎，建议降低车速，注意货物防风保护`,
      type: 'wind'
    })
  } else if (windSpeed >= 4) {
    alerts.push({
      level: 'medium',
      title: '风力提醒',
      description: `风速${windSpeed}m/s，运输基本正常，建议注意货物固定`,
      type: 'wind'
    })
  } else if (windSpeed >= 2) {
    alerts.push({
      level: 'low',
      title: '微风提醒',
      description: `风速${windSpeed}m/s，运输条件良好，建议注意货物固定`,
      type: 'wind'
    })
  }
  
  // 能见度预警 - 进一步降低阈值
  const visibility = parseFloat(weather.visibility)
  if (visibility < 3) {
    alerts.push({
      level: 'severe',
      title: '大雾预警',
      description: `能见度${visibility}km，物流运输严重受阻，建议暂停运输或使用GPS导航系统`,
      type: 'visibility'
    })
  } else if (visibility < 8) {
    alerts.push({
      level: 'high',
      title: '雾霾预警',
      description: `能见度${visibility}km，运输需谨慎，建议降低车速，开启雾灯`,
      type: 'visibility'
    })
  } else if (visibility < 15) {
    alerts.push({
      level: 'medium',
      title: '能见度提醒',
      description: `能见度${visibility}km，运输基本正常，建议注意观察路况`,
      type: 'visibility'
    })
  } else if (visibility < 25) {
    alerts.push({
      level: 'low',
      title: '能见度提醒',
      description: `能见度${visibility}km，运输条件良好，建议注意观察路况`,
      type: 'visibility'
    })
  }
  
  // 综合天气预警 - 添加物流提示
  const description = weather.description.toLowerCase()
  if (description.includes('雷') || description.includes('暴')) {
    alerts.push({
      level: 'severe',
      title: '雷暴预警',
      description: '检测到雷暴天气，物流运输严重危险，建议暂停所有运输活动，等待天气好转',
      type: 'storm'
    })
  }
  
  if (description.includes('雪')) {
    alerts.push({
      level: 'high',
      title: '雪天预警',
      description: '检测到雪天，道路湿滑影响运输安全，建议使用防滑链，降低车速',
      type: 'storm'
    })
  }
  
  if (description.includes('雹')) {
    alerts.push({
      level: 'severe',
      title: '冰雹预警',
      description: '检测到冰雹天气，可能损坏货物和车辆，建议立即寻找避护场所',
      type: 'storm'
    })
  }
  
  if (description.includes('沙') || description.includes('尘')) {
    alerts.push({
      level: 'high',
      title: '沙尘预警',
      description: '检测到沙尘天气，影响货物清洁度，建议加强货物包装保护',
      type: 'visibility'
    })
  }
  
  // 湿度预警 - 进一步降低阈值
  const humidity = parseFloat(weather.humidity)
  if (humidity >= 75) {
    alerts.push({
      level: 'medium',
      title: '高湿度提醒',
      description: `湿度${humidity}%，货物易受潮，建议加强防潮包装，注意货物存储环境`,
      type: 'temperature'
    })
  } else if (humidity >= 60) {
    alerts.push({
      level: 'low',
      title: '湿度提醒',
      description: `湿度${humidity}%，湿度较高，建议注意货物防潮`,
      type: 'temperature'
    })
  } else if (humidity <= 35) {
    alerts.push({
      level: 'low',
      title: '低湿度提醒',
      description: `湿度${humidity}%，货物易干燥，建议注意货物保湿保护`,
      type: 'temperature'
    })
  } else if (humidity <= 50) {
    alerts.push({
      level: 'low',
      title: '湿度提醒',
      description: `湿度${humidity}%，湿度较低，建议注意货物保湿`,
      type: 'temperature'
    })
  }
  
  return alerts
}

// 获取单个点位的天气
const getPointWeather = async (point: MiddlePoint, index: number) => {
  point.loading = true
  point.error = undefined
  
  try {
    const weatherResponse = await WeatherService.getForecastByCoordinates(
      point.latitude, 
      point.longitude
    )
    
    const weatherData = parseWeatherData(weatherResponse)
    const alerts = checkWeatherAlerts(weatherData)
    
    point.weather = weatherData
    point.alerts = alerts
    point.loading = false
    
    console.log(`${point.name}天气获取成功:`, weatherData)
  } catch (err: any) {
    point.loading = false
    point.error = err.response?.data?.message || err.message || '获取天气数据失败'
    console.error(`${point.name}天气获取失败:`, err)
  }
}

// 刷新单个点位天气
const refreshPointWeather = async (index: number) => {
  const point = middlePoints.value[index]
  if (point) {
    await getPointWeather(point, index)
  }
}

// 生成路线预警
const generateRouteAlerts = () => {
  const alerts: RouteAlert[] = []
  
  // 收集所有严重和高危预警
  const alertGroups: { [key: string]: { alerts: WeatherAlert[], locations: string[] } } = {}
  
  middlePoints.value.forEach(point => {
    if (point.alerts) {
      point.alerts.forEach(alert => {
        // 包含所有级别的预警，让平常数据也能显示
        if (alert.level === 'severe' || alert.level === 'high' || alert.level === 'medium' || alert.level === 'low') {
          if (!alertGroups[alert.type]) {
            alertGroups[alert.type] = { alerts: [], locations: [] }
          }
          alertGroups[alert.type].alerts.push(alert)
          alertGroups[alert.type].locations.push(point.name)
        }
      })
    }
  })
  
  // 生成路线预警
  Object.entries(alertGroups).forEach(([type, group]) => {
    const locations = [...new Set(group.locations)] // 去重
    const alert = group.alerts[0] // 取第一个预警作为代表
    
    // 根据预警类型添加物流建议
    let logisticsAdvice = ''
    switch (alert.type) {
      case 'temperature':
        if (alert.level === 'high') {
          logisticsAdvice = '建议调整运输时间，避开极端温度时段，加强货物温度保护'
        } else if (alert.level === 'medium') {
          logisticsAdvice = '建议注意货物温度保护，适当调整运输时间'
        } else if (alert.level === 'low') {
          logisticsAdvice = '建议关注货物温度变化，做好防护准备'
        }
        break
      case 'rain':
        if (alert.level === 'severe') {
          logisticsAdvice = '建议暂停公路运输，考虑铁路或航空运输替代方案'
        } else if (alert.level === 'high') {
          logisticsAdvice = '建议降低运输速度，加强货物防水保护措施'
        } else if (alert.level === 'medium') {
          logisticsAdvice = '建议注意货物防潮，适当调整运输计划'
        } else if (alert.level === 'low') {
          logisticsAdvice = '建议关注天气变化，做好防潮准备'
        }
        break
      case 'wind':
        if (alert.level === 'severe') {
          logisticsAdvice = '建议暂停大型车辆运输，小型车辆需加强货物固定'
        } else if (alert.level === 'high') {
          logisticsAdvice = '建议降低运输速度，加强货物防风固定'
        } else if (alert.level === 'medium') {
          logisticsAdvice = '建议注意货物固定，确保运输安全'
        } else if (alert.level === 'low') {
          logisticsAdvice = '建议关注风力变化，做好货物固定准备'
        }
        break
      case 'visibility':
        if (alert.level === 'severe') {
          logisticsAdvice = '建议暂停运输或使用GPS导航，确保运输安全'
        } else if (alert.level === 'high') {
          logisticsAdvice = '建议降低运输速度，开启雾灯，谨慎驾驶'
        } else if (alert.level === 'medium') {
          logisticsAdvice = '建议注意观察路况，保持安全距离'
        } else if (alert.level === 'low') {
          logisticsAdvice = '建议关注能见度变化，谨慎驾驶'
        }
        break
      case 'storm':
        if (alert.level === 'severe') {
          logisticsAdvice = '建议立即暂停所有运输活动，等待天气好转'
        } else if (alert.level === 'high') {
          logisticsAdvice = '建议使用防滑设备，降低运输速度'
        } else if (alert.level === 'medium') {
          logisticsAdvice = '建议关注特殊天气变化，做好防护准备'
        } else if (alert.level === 'low') {
          logisticsAdvice = '建议关注天气变化，做好应急准备'
        }
        break
    }
    
    alerts.push({
      level: alert.level,
      title: `路线${alert.title}`,
      description: `${alert.description}，影响路段：${locations.join(' → ')}。物流建议：${logisticsAdvice}`,
      locations,
      type: alert.type as any
    })
  })
  
  routeAlerts.value = alerts
  
  // 显示预警通知
  if (alerts.length > 0) {
    const severeCount = alerts.filter(a => a.level === 'severe').length
    const highCount = alerts.filter(a => a.level === 'high').length
    const mediumCount = alerts.filter(a => a.level === 'medium').length
    const lowCount = alerts.filter(a => a.level === 'low').length
    
    if (severeCount > 0) {
      ElMessage({
        message: `🚛 路线严重天气预警：检测到${severeCount}个严重预警，物流运输严重受阻，建议暂停运输或调整运输方案`,
        type: 'error',
        duration: 12000,
        showClose: true
      })
    } else if (highCount > 0) {
      ElMessage({
        message: `🚛 路线天气预警：检测到${highCount}个高危预警，物流运输需谨慎，建议调整运输计划`,
        type: 'warning',
        duration: 10000,
        showClose: true
      })
    } else if (mediumCount > 0) {
      ElMessage({
        message: `🚛 路线天气提醒：检测到${mediumCount}个中等预警，物流运输需注意，建议关注天气变化`,
        type: 'warning',
        duration: 8000,
        showClose: true
      })
    } else if (lowCount > 0) {
      ElMessage({
        message: `🚛 路线天气提醒：检测到${lowCount}个低风险提醒，物流运输基本正常，建议关注天气变化`,
        type: 'info',
        duration: 6000,
        showClose: true
      })
    }
  }
}

// 获取路线天气
const getRouteWeather = async () => {
  if (!props.startAddress) {
    ElMessage.warning('请输入起点地址')
    return
  }
  
  loading.value = true
  error.value = ''
  
  try {
    // 获取起点和终点坐标
    const startCoords = await addressToCoordinates(props.startAddress)
    const endCoords = await addressToCoordinates(props.endAddress)
    
    console.log('起点坐标:', startCoords)
    console.log('终点坐标:', endCoords)
    
    // 计算中间点
    const points = calculateMiddleCities(
      startCoords.lat, startCoords.lng,
      endCoords.lat, endCoords.lng
    )
    
    middlePoints.value = points
    
    // 并行获取所有中间点的天气
    const weatherPromises = points.map((point, index) => getPointWeather(point, index))
    await Promise.all(weatherPromises)
    
    // 生成路线预警
    generateRouteAlerts()
    
    ElMessage.success('路线天气数据获取成功')
  } catch (err: any) {
    console.error('获取路线天气失败:', err)
    error.value = err.response?.data?.message || err.message || '获取路线天气数据失败'
    ElMessage.error(error.value)
  } finally {
    loading.value = false
  }
}

// 刷新天气
const refreshWeather = () => {
  getRouteWeather()
}

// 生命周期
onMounted(() => {
  if (props.startAddress) {
    getRouteWeather()
  }
})
</script>

<style scoped>
.route-weather-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
  border-radius: 12px;
  border-left: 4px solid #409eff;
}

.route-info {
  flex: 1;
}

.route-points {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.point {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  border-radius: 8px;
  font-weight: 500;
}

.start-point {
  background: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.end-point {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.route-arrow {
  color: #666;
  font-size: 18px;
}

.route-distance {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.route-controls {
  flex-shrink: 0;
}

/* 路线预警总览 */
.route-alerts-overview {
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #fff5f5, #fef0f0);
  border-radius: 12px;
  border-left: 4px solid #f56c6c;
}

.overview-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  color: #f56c6c;
}

.overview-alerts {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.overview-alert-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.overview-alert-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.overview-alert-item.alert-low {
  background: #f0f9ff;
  border-left: 3px solid #409eff;
}

.overview-alert-item.alert-medium {
  background: #fef7e0;
  border-left: 3px solid #e6a23c;
}

.overview-alert-item.alert-high {
  background: #fef0f0;
  border-left: 3px solid #f56c6c;
}

.overview-alert-item.alert-severe {
  background: #fef0f0;
  border-left: 3px solid #f56c6c;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.8; }
}

.alert-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 5px;
}

.alert-description {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 5px;
}

.alert-locations {
  font-size: 13px;
  color: #999;
  font-weight: 500;
}

/* 中间点天气详情 */
.middle-points-weather {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.points-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.weather-point-card {
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.weather-point-card:hover {
  background: #f0f9ff;
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.weather-point-card.loading {
  background: #f8f9fa;
  border-color: #409eff;
}

.weather-point-card.error {
  background: #fef0f0;
  border-color: #f56c6c;
}

.point-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.point-info {
  flex: 1;
}

.point-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.point-distance {
  font-size: 13px;
  color: #666;
}

.point-status {
  flex-shrink: 0;
}

.loading-icon {
  color: #409eff;
  animation: spin 1s linear infinite;
}

.error-icon {
  color: #f56c6c;
}

.success-icon {
  color: #67c23a;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 天气信息 */
.weather-info {
  margin-bottom: 15px;
}

.current-weather {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.temperature {
  display: flex;
  align-items: baseline;
  gap: 5px;
}

.temp-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
}

.temp-unit {
  font-size: 18px;
  color: #666;
}

.weather-desc {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.weather-text {
  font-size: 16px;
  font-weight: 500;
}

.rainfall {
  padding: 8px 12px;
  background: linear-gradient(135deg, #409eff, #67c23a);
  border-radius: 6px;
  text-align: center;
}

.rainfall-text {
  font-size: 13px;
  font-weight: 600;
  color: white;
}

.weather-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 13px;
}

/* 点位预警 */
.point-alerts {
  margin-top: 15px;
}

.point-alert-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 8px;
}

.point-alert-item.alert-low {
  background: #f0f9ff;
  border-left: 3px solid #409eff;
}

.point-alert-item.alert-medium {
  background: #fef7e0;
  border-left: 3px solid #e6a23c;
}

.point-alert-item.alert-high {
  background: #fef0f0;
  border-left: 3px solid #f56c6c;
}

.point-alert-item.alert-severe {
  background: #fef0f0;
  border-left: 3px solid #f56c6c;
}

.point-alert-item .alert-icon {
  flex-shrink: 0;
  margin-top: 1px;
}

.point-alert-item .alert-content {
  flex: 1;
}

.point-alert-item .alert-title {
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 3px;
}

.point-alert-item .alert-description {
  font-size: 12px;
  color: #666;
  line-height: 1.3;
}

/* 错误信息 */
.error-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px;
  background: #fef0f0;
  border-radius: 8px;
  color: #f56c6c;
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  margin: 40px 0;
}

.loading-content,
.error-content {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .route-weather-container {
    padding: 10px;
  }
  
  .route-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .route-points {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .route-arrow {
    transform: rotate(90deg);
  }
  
  .points-grid {
    grid-template-columns: 1fr;
  }
  
  .current-weather {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .weather-details {
    grid-template-columns: 1fr;
  }
}
</style>
